#include "Thread.h"
#include "CurrentThread.h"
#include <semaphore.h>

std::atomic_int Thread::numCreated_ = std::atomic_int(0);

Thread::Thread(ThreadFunc func, const std::string &n) 
    : started_(false)
    , joined_(false)
    , tid_(0)
    , func_(std::move(func))
    , name_(n)
{
    setDefaultName();
}
Thread::~Thread() {
    if (started_ && !joined_) {
        thread_->detach();//分离线程
    }
}

void Thread::start() {
    started_ = true;

    sem_t sem;
    sem_init(&sem, false, 0); // 信号量保证线程id即tid_被拿到

    thread_ = std::shared_ptr<std::thread> (new std::thread([&](){
        tid_ = CurrentThread::tid();
        sem_post(&sem); //能解除sem_wait的阻塞

        func_(); // 开启新线程，执行线程函数
    }));

    sem_wait(&sem);
}

void Thread::join() {
    joined_ = true;
    thread_->join();//调用join，主线程是阻塞的，等待子线程的终止，回收子线程
}



void Thread::setDefaultName() {
    int num = ++numCreated_;
    if (name_.empty()) {
        char buf[32];
        snprintf(buf, sizeof buf, "Thread%d", num);
        name_ = buf;
    }
}